# @Time    :2025/4/24 18:36
# python 连接数据库
import pymysql


# 获取连接
def get_connection():
    try:
        conn = pymysql.connect(
            #host='127.0.0.1',  # 连接的本地地址
            host='192.168.10.150',  # 连接的服务器上的地址
            port=3306,
            user='root',
            password='qwerluu',
            database='atguigu',
            charset='utf8mb4',
            cursorclass=pymysql.cursors.DictCursor  # 通过叫cursors游标的方式封装成字典
        )
        return conn
    except:
        print("获取连接的时候发生了异常 ")
# 从数据库中查询数据
def select_data(conn):
    global cursor
    try:
        # 创建游标对象
        cursor = conn.cursor()
        # 执行sql语句
        sql = "select * from t_department"
        cursor.execute(sql)
        # 获取查询结果
        result = cursor.fetchall()
        # 遍历结果
        for item in result:
            print(item)
    except:
        print("查询数据时候发生了异常")
    finally:
        cursor.close()

    #插入数据
def insert_data(conn):
    try:
        cursor = conn.cursor()
        sql = "insert into t_department values(10,'test','做测试工作...')"
        cursor.execute(sql)
       # sql = "insert into t_department values(%s,%s)"
       # cursor.execute(sql, (5, "测试部"))
        conn.commit()
        print("插入数据成功")
        return True
    except:
        conn.rollback()
        print("插入数据时候发生了异常")
        return False
    finally:
        cursor.close()
        return True
def update_data(conn):
    try:
        cursor = conn.cursor()
        sql = "update t_department set dname='dev' where did=10"
        cursor.execute(sql)
        conn.commit()
        print("更新数据成功")
        return True
    except:
        conn.rollback()
        print("更新数据时候发生了异常")
        return False
    finally:
        cursor.close()
        return True
#删除连接数据
def delete_data(conn):
    try:
        cursor = conn.cursor()
        sql = "delete from t_department where did=10"
        cursor.execute(sql)
        conn.commit()
        print("删除数据成功")
        return True
    except:
        conn.rollback()
        print("删除数据时候发生了异常")
        return False
    finally:
        cursor.close()
        return True

if __name__ == '__main__':
    conn = get_connection()
    #select_data(conn)
   # insert_data(conn)
    #update_data(conn)
    delete_data(conn)
    select_data(conn)


   # conn.close()